package com.lmx.config;

import com.lmx.dao.Message;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

@Controller
@ServerEndpoint("/socket/chat")
// ServerEndpoint中为请求资源路径
public class MySocket {
    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        System.out.println(session.getId());


        Message.map.put(session.getId(),session);
        try {
            // 发送数据
            session.getBasicRemote().sendText("连接成功");
        } catch (IOException e) {
            e.printStackTrace();

            try {
                // 关闭连接
                session.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        Message.map.remove(session.getId());
        System.out.println("关闭连接");
    }

    @OnError
    public void onError(Session session, Throwable thr) {
        System.out.println("发生错误");
    }

    @OnMessage
    public void onMessage(String message,Session session) {
        String id = session.getId();
//        System.out.println(id);
//        System.out.println("收到消息:" + message);
        info(message);
    }
    private void info(String str){
        Collection<Session> values = Message.map.values();
        Object[] objects = values.toArray();
        for (Object object : objects) {
            try {
                ((Session) object).getBasicRemote().sendText(str);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }}
